package com.geoboard;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.LinkedList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.os.AsyncTask;
import android.widget.Toast;

/**
 * Retrieves a list of messages from the server 
 * in a background thread.
 * @author Gordon Meyer 03/13
 */
public class GetMessages extends AsyncTask<Void,Void,String>{
	
	private String url = "";
	
	
	public GetMessages(){}	

	/**
	 * Will make an HTTP GET request of the server.
	 * Runs in a separate thread in the background.
	 */
	@Override
	protected String doInBackground(Void... params) {
		url += Globals.SERVER_ADD + ":" + Globals.SERVER_PORT + "?";
		
		double lat = PositionManager.getLocation().getLatitude();
		double lng =PositionManager.getLocation().getLongitude();
		
		// create encoded url for request
		try {
			url += "lat=" + URLEncoder.encode(String.valueOf(lat),"UTF-8") + "&long=" + URLEncoder.encode(String.valueOf(lng),"UTF-8") + 
					"&numPosts=50";
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		HttpParams hp = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(hp, Globals.CON_TIME_OUT);
		HttpConnectionParams.setSoTimeout(hp, Globals.SOC_TIME_OUT);
		
		HttpClient client = new DefaultHttpClient(hp);
		HttpGet get = new HttpGet(url);
		
		HttpResponse response = null;
		
		// make the request
		try {
			response = client.execute(get);
		} catch(HttpHostConnectException e){
			return "Conection to host refused.";
		} catch (Exception e){
			return e.toString();
		}
		
		
		BufferedReader reader = null;
		StringBuilder builder = new StringBuilder();
		String line = null;
		
		// parse response
		if(response != null){
			try {
				reader = new BufferedReader(
							new InputStreamReader(response.getEntity().getContent()));
				
				line = reader.readLine();
				while(line != null){
					builder.append(line);
					line = reader.readLine();
				}
				
			
			} catch (Exception e){
				return "Unable to parse response.";
			}
		}
		
		// make linkedlist of messages
		String r = builder.toString();
		LinkedList<Post> messages;
		
		Type type = new TypeToken<LinkedList<Post>>(){}.getType();
		
		Gson gson = new Gson();
		// use GSON to transform response to Post object
		messages = gson.fromJson(r, type);		
				
		MessageManager.processMessages(messages);
		
		return null;
	}
	
	/**
	 * Executes on main thread after HTTP request is finished.
	 * If there was an error display it to the user, else
	 * display the retrieved messages.
	 */
	@Override
	protected void onPostExecute(String response) {
		if(response != null){
			Toast.makeText(Globals.getContext(), response,
			        Toast.LENGTH_SHORT).show();
		} else {
			MessageManager.displayNewMessages();			
		}
		MessageManager.onGetComplete();
    }

}
